package main

import "fmt"

func main() {
	nums := []int{1, 3, 5, 6}
	target := 5
	fmt.Println(searchInsert(nums, target))
	target = 2
	fmt.Println(searchInsert(nums, target))
	target = 7
	fmt.Println(searchInsert(nums, target))
	target = 0
	fmt.Println(searchInsert(nums, target))

}

/**
 * @Description: 给定一个排序数组和一个目标值，在数组中找到目标值，并返回其索引。如果目标值不存在于数组中，返回它将会被按顺序插入的位置。
 * @t: 利用左二分法
 */
func searchInsert(nums []int, target int) int {
	left, right := 0, len(nums)
	for left < right {
		mid := left + (right-left)/2
		if midNum := nums[mid]; midNum == target {
			right = mid
		} else if midNum < target {
			left = mid + 1
		} else if midNum > target {
			right = mid
		}
	}
	return left
}
